/**
 * Created by zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/11/24
 * Time: 00:18
 */
$(function(){
    $.ajax({
        type: 'get',
        url: '/categories.json',
        success: function(e){
            var data = JSON.parse(e);
            if (data.status == 200) {
                var json = data.body.data;
                if (json.length > 0) {
                    $.each(json, function(n, v){
                        var html = '<option value="'+v.id+'">'+ v.name+'</option>';
                        $('.category').append(html);
                    });
                }
            }
        }
    });

    var authorization = Cookies.get('_token');
    $('.btn-save').on('click', function(){
        var params = {
            title: $('.title').val(),
            category: $('.category').val(),
            desc: $('.desc').val(),
            content: $('.content').val()
        };
        if (checkForm(params)) {
            $.ajax({
                type: 'post',
                url: '/v1/student/saveWork',
                headers: {
                    Authorization: authorization,
                    Accept: "application/json; charset=utf-8"
                },
                data: {params: params},
                success: function(e){
                    var data = JSON.parse(e);
                    if (data.status == 200) {
                        alert('添加成功');
                        location.href = '/student/work.html';
                    }
                }
            });
        }
    });
});

function checkForm(params) {
    if (params.title == '') {
        alert('请输入作品名称!');
        return false;
    }
    if (params.category == '') {
        alert('请选择作品分类!');
        return false;
    }
    if (params.content == '') {
        alert('请上传作品!');
        return false;
    }
    return true;
}